package com.example.fw;

import java.util.List;
import java.util.Random;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.example.tests.ContactData;
import com.example.utils.SortedListOf;

public class ContactHelper extends MainHelper{

	public ContactHelper(ApplicationManager appManager) {
		super(appManager);
	}

//------------------ High level methods-------------------------------------------------
	public ContactHelper fillContactForm(ContactData contactInput) {
		type(By.name("firstname"), contactInput.firstName);
	    type(By.name("lastname"), contactInput.lastName);;    
		type(By.name("address"), contactInput.firstAddress);
		type(By.name("home"), contactInput.homePhone);
		type(By.name("mobile"), contactInput.mobilePhone);
		type(By.name("work"), contactInput.workPhone);
		type(By.name("email"), contactInput.firstEmail);
		type(By.name("email2"), contactInput.secondEmail);
		selectByText(By.name("bday"), contactInput.bDay);
		selectByText(By.name("bmonth"), contactInput.bMonth);
		type(By.name("byear"), contactInput.bYear);	
		selectByText(By.name("new_group"), contactInput.groupLinkage);									
		type(By.name("address2"), contactInput.secondAddress);
		type(By.name("phone2"), contactInput.secondPhone);
		return this;
	}
	
	public SortedListOf<ContactData> cachedContacts;
	
	public SortedListOf<ContactData> getContacts() {
		if (cachedContacts == null) {
			rebuildCachedContacts();
		}
		return cachedContacts;
	}
	
	public void rebuildCachedContacts() {
			SortedListOf<ContactData> cachedContacts = new SortedListOf<ContactData>();
			appManager.getNaviHelper().openMainPage();
			List<WebElement> rows = getContactRows();						
			for (WebElement row : rows) {
				ContactData contact = new ContactData();
														
				contact.lastName = getLastNameInRow(row);
				if(contact.lastName == null){
						contact.lastName = ""; 
				}
				
				contact.firstName = getFirstNameInRow(row);
				if(contact.firstName == null ){
						contact.firstName = ""; 				
				}
				cachedContacts.add(contact);
			}	
	}

	public String randomGroup() {
		List<WebElement> groupLink = driver.findElements(By.xpath("//select[@name='new_group']"));
		String randomGroups = "";
		if(groupLink.size() != 0){
			Random rnd = new Random();
			SortedListOf<String>  groupsList = getGroupListForContact();
			String[] array = groupsList.toArray(new String[groupsList.size()]);
			int r = rnd.nextInt(array.length);
			randomGroups = array[r];			
		}
		return randomGroups;
	}
	
	public SortedListOf<Integer> getContactId(){
		SortedListOf<Integer> contactId = new SortedListOf<Integer>();
		appManager.getNaviHelper().openMainPage();
		List<WebElement> checkboxes = driver.findElements(By.xpath("//tr[@name=\"entry\"]/td[@class=\"center\"]/input[@type=\"checkbox\"][@name=\"selected[]\"]"));		
		for (WebElement checkbox : checkboxes) {			
			String idx = checkbox.getAttribute("value");
			int index = Integer.parseInt(idx);						  
	        contactId.add(index);
		}
		return contactId;
	}
	
	public SortedListOf<String> cashedGroupsForContacts;
	
	public SortedListOf<String> getGroupListForContact(){  
		if (cashedGroupsForContacts == null) {
			rebuildCachedGroupsForContacts();
		}
		return cashedGroupsForContacts;
	}		
	
    public void rebuildCachedGroupsForContacts() {			
        	SortedListOf<String> cashedGroupsForContacts = new SortedListOf<String>();
        	appManager.getNaviHelper().openMainPage();
            List<WebElement> allGroupsOptions = driver.findElements(By.xpath("//select[@name='new_group']/option"));
            int optionCount = driver.findElements(By.xpath("//select[@name='new_group']/option")).size();
            for (int j = 1; j <= optionCount; j++) {
                  for(WebElement element : allGroupsOptions){
                  String      dropDown = element.getText();
                  cashedGroupsForContacts.add(dropDown);
                  }                      
            }
	}    
    
    public ContactHelper creationContact(ContactData contactInput) {
		appManager.getNaviHelper().openMainPage();
		appManager.getNaviHelper().clickOnAddNewButton();
		fillContactForm(contactInput);			
		appManager.getNaviHelper().submitNewCreation();
		appManager.getNaviHelper().openMainPage();
		rebuildCachedContacts();
		return this;
	}

	public ContactHelper deletionContact(int element) {
		appManager.getNaviHelper().openMainPage();
		initContactModification(element);
		submitContactDeletion();				
		appManager.getNaviHelper().openMainPage();
		//rebuildCachedContacts();
		return this;
	}

	public ContactHelper modifyContact(int element, ContactData contactInput) {
		appManager.getNaviHelper().openMainPage();
		initContactModification(element);					
		fillContactForm(contactInput);
		submitContactModification();
		appManager.getNaviHelper().openMainPage();
		//rebuildCachedContacts();
		return this;			
	}

//------------------ Low level methods-------------------------------------------------	
	
		public String getFirstNameInRow(WebElement row) {				
			return row.findElement(By.xpath("./td[2]")).getText();
		}

		public String getLastNameInRow(WebElement row) {			
			return row.findElement(By.xpath("./td[3]")).getText();
		}

		private List<WebElement> getContactRows() {
			return driver.findElements(By.xpath("//tr[@name='entry']"));
		}
		
		public void initContactModification(int index) {		
			click(By.xpath("//a[@href=\"edit.php?id=" + index + "\"]"));
		}

		public ContactHelper submitContactDeletion() {
			click(By.xpath("//input[@value = 'Delete']"));
			cachedContacts = null;
			return this;
		}  
		
		public ContactHelper submitContactModification() {
			click(By.xpath("//input[@value = 'Update']"));	
			cachedContacts = null;
			return this;
		}

}		
		
/*		public List<ContactData> getGroupsForContact() {
			List<ContactData> groupsDropDownValues = new ArrayList<ContactData>();
			List<WebElement> groupsDropDownElement = driver.findElements(By.xpath("//select[@name='new_group']/option"));	
			for (WebElement element : groupsDropDownElement) {
				ContactData groups = new ContactData();
				groups.groupLinkage = element.getText();
				if(groups.groupLinkage == null ){
					groups.groupLinkage = ""; 
				}
				groupsDropDownValues.add(groups);
			}
			return groupsDropDownValues;
		}*/
		/*List<WebElement> checkboxes = driver.findElements(By.xpath("//tr[@name=\"entry\"]/td[@class=\"center\"]/input[@type=\"checkbox\"][@name=\"selected[]\"]"));		
		for (WebElement checkbox : checkboxes) {
			ContactData contact = new ContactData();
			String title = checkbox.getAttribute("title");
			//regexp matcher
			Pattern pattern = Pattern.compile("^Select\\((?:([a-zA-Z0-9]+)\\s+([a-zA-Z0-9]+))\\)$");
			Matcher matcher = pattern.matcher(title);
			if (matcher.matches()) {
			   //String x = matcher.group(1); 
			   contact.lastName = matcher.group(2); 
			}
			if(contact.lastName == null ){
				contact.lastName = ""; 
			}					
			contacts.add(contact);
		}
		return contacts;
	}  */
	
			

